import Mock from 'mockjs';
import echarts from 'echarts/lib/echarts';

export const departments = ['生活', '家用', '厨热', '冰箱', '楼宇', '工业技术', '洗衣机', '微清', '电子公司'];
export const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

// 生成趋势数据
function generateTrendData(baseValue, variance) {
  return months.map(month => {
    const value = Mock.Random.float(baseValue - variance, baseValue + variance).toFixed(2);
    return {
      month,
      value: parseFloat(value),
      total: Math.round(parseFloat(value) * 100),
      completed: Math.round(parseFloat(value) * 100 * parseFloat(value) / 100)
    };
  });
}

// 生成部门对比数据
function generateDepartmentData(baseValue, variance) {
  return departments.map(department => {
    const value = Mock.Random.float(baseValue - variance, baseValue + variance).toFixed(2);
    return {
      department,
      value: parseFloat(value),
      total: Math.round(parseFloat(value) * 100),
      completed: Math.round(parseFloat(value) * 100 * parseFloat(value) / 100)
    };
  });
}

// 生成数字化工具使用数据
function generateToolsData() {
  const tools = [
    { name: '电路库调用', details: ['模块电路库', 'PCB外形尺寸库', 'PCB模块调用'] },
    { name: '设计辅助工具', details: ['参数计算器', '器件更新', '器件替换', '封装一键替换', '布局传递到PCB', '跳线反标', '复制变量'] },
    { name: '原理图检查', details: ['原理图检查'] },
    { name: 'PCB检查', details: ['PCB检查'] },
    { name: '在线评审工具', details: ['Checklist检查', '在线化评审'] },
    { name: 'BOM导出', details: ['BOM导出'] },
    { name: 'BOM一致性测试', details: ['BOM一致性测试'] },
    { name: '快捷工具', details: ['跳转EDM', '跳转plm', '缓存清理'] }
  ];
  
  return tools.map(tool => {
    const value = Mock.Random.float(50, 95).toFixed(2);
    const detailsData = tool.details.map(detail => {
      return {
        name: detail,
        value: Mock.Random.float(30, 95).toFixed(2),
        count: Mock.Random.integer(100, 1000)
      };
    });
    
    return {
      name: tool.name,
      value: parseFloat(value),
      details: detailsData
    };
  });
}

// 生成数字化应用趋势数据
function generateDigitalTrendData() {
  const toolScores = {};
  departments.forEach(dept => {
    toolScores[dept] = generateToolsData().map(tool => tool.value);
  });
  
  return months.map((month, index) => {
    const deptData = {};
    departments.forEach(dept => {
      deptData[dept] = toolScores[dept].map(score => {
        let trend = index < 6 ? index * 0.5 : (11 - index) * 0.3;
        return Math.min(95, Math.max(50, score + trend + Mock.Random.float(-2, 2)));
      }).reduce((a, b) => a + b, 0) / 8;
    });
    
    return {
      month,
      ...deptData
    };
  });
}

// 准备按事业部的趋势数据
//metric: 字符串类型，指定要生成的指标类型（'component', 'circuit', 'doc' 或其他）
//baseData: 包含各部门基础值的对象
//colorStart: 颜色渐变的起始颜色
//colorEnd: 颜色渐变的结束颜色
function prepareDataByDepartment(metric, baseData, colorStart, colorEnd) {
  const result = [];
  // 遍历部门数据
  departments.forEach((dept, deptIndex) => {
    
    const series = {
      name: dept + (metric === 'component' ? '-器件入库率' : 
                   metric === 'circuit' ? '-电路维护率' :
                   metric === 'doc' ? '-项目文档交付率' : '-工程文件交付率'),
      type: 'line',
      data: months.map((_, monthIndex) => {
        const baseValue = baseData.byDepartment[deptIndex].value;
        const monthOffset = (monthIndex / 11) * 0.1 - 0.05;
        return Math.min(1, Math.max(0.6, baseValue + monthOffset + Mock.Random.float(-0.02, 0.02)));
      }),
      lineStyle: {
        width: 2,
        color: echarts.color.lerp(deptIndex/departments.length, [colorStart, colorEnd])
      },
      itemStyle: {
        color: echarts.color.lerp(deptIndex/departments.length, [colorStart, colorEnd])
      },
      smooth: true,
      showSymbol: false
    };
    result.push(series);
  });
  
  return result;
}

// 准备数字化工具详细数据
function prepareToolsDetailData(toolsData) {
  const categories = toolsData.map(tool => tool.name);
  const series = [];
  
  const allDetails = {};
  toolsData.forEach(tool => {
    tool.details.forEach(detail => {
      if (!allDetails[tool.name]) {
        allDetails[tool.name] = [];
      }
      allDetails[tool.name].push(detail);
    });
  });

  Object.keys(allDetails).forEach(toolName => {
    const details = allDetails[toolName];
    details.forEach(detail => {
      series.push({
        name: `${toolName}-${detail.name}`,
        type: 'bar',
        stack: toolName,
        emphasis: {
          focus: 'series'
        },
        data: categories.map(cat => {
          if (cat === toolName) {
            return {
              value: detail.count,
              itemStyle: {
                color: generateColorByName(detail.name)
              }
            };
          } else {
            return 0;
          }
        })
      });
    });
  });

  return {
    categories,
    series
  };
}

// 根据名称生成颜色
function generateColorByName(name) {
  const colors = {
    '模块电路库': '#1890ff',
    'PCB外形尺寸库': '#36cfc9',
    'PCB模块调用': '#73d13d',
    '参数计算器': '#ffc53d',
    '器件更新': '#ff7a45',
    '器件替换': '#f759ab',
    '封装一键替换': '#722ed1',
    '布局传递到PCB': '#2f54eb',
    '跳线反标': '#52c41a',
    '复制变量': '#fadb14',
    '原理图检查': '#fa541c',
    'PCB检查': '#fa8c16',
    'Checklist检查': '#eb2f96',
    '在线化评审': '#b37feb',
    'BOM导出': '#85a5ff',
    'BOM一致性测试': '#597ef7',
    '跳转EDM': '#ff85c0',
    '跳转plm': '#ffbb96',
    '缓存清理': '#13c2c2'
  };
  
  return colors[name] || '#1890ff';
}

// 准备数字化工具按部门数据
function prepareDigitalToolsByDepartment(toolsData) {
  const categories = toolsData.map(tool => tool.name);
  const series = departments.map((dept, deptIndex) => {
    const baseValue = 50 + deptIndex * 3;
    const values = categories.map((_, toolIndex) => {
      const variance = Math.sin(deptIndex * 0.5 + toolIndex * 0.8) * 15;
      return Math.min(95, Math.max(30, baseValue + variance + Mock.Random.float(-5, 5)));
    });
    
    return {
      name: dept,
      type: 'line',
      data: values,
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      emphasis: {
        focus: 'series',
        lineStyle: {
          width: 4
        }
      }
    };
  });
  
  return {
    categories,
    series
  };
}

// 准备工具使用趋势数据
function prepareToolsUsageTrendData() {
  const departmentData = {};
  departments.forEach(dept => {
    departmentData[dept] = months.map((_, monthIndex) => {
      const baseValue = 60 + Mock.Random.float(0, 20);
      
      let toolDetails = {};
      generateToolsData().forEach(tool => {
        toolDetails[tool.name] = tool.details.map(detail => {
          const monthFactor = monthIndex < 6 ? 
            monthIndex * 2 : 
            10 + (monthIndex - 6) * 0.5;
          
          return {
            name: detail.name,
            value: Math.min(95, Math.max(30, baseValue + monthFactor + Mock.Random.float(-8, 8)))
          };
        });
      });
      
      let totalValue = 0;
      Object.values(toolDetails).forEach(details => {
        details.forEach(detail => {
          totalValue += detail.value;
        });
      });
      
      totalValue = Math.min(95, Math.max(30, totalValue / 20));
      
      return {
        month: months[monthIndex],
        value: totalValue,
        details: toolDetails
      };
    });
  });
  
  return departmentData;
}

export function generateData() {
  // 生成基础数据
  const componentStorage = {
    trend: generateTrendData(0.85, 0.1),
    byDepartment: generateDepartmentData(0.85, 0.15),
    trendSeries: prepareDataByDepartment('component', { byDepartment: generateDepartmentData(0.85, 0.15) }, '#1890ff', '#36cfc9')
  };
  
  const circuitMaintenance = {
    trend: generateTrendData(0.78, 0.12),
    byDepartment: generateDepartmentData(0.78, 0.18),
    trendSeries: prepareDataByDepartment('circuit', { byDepartment: generateDepartmentData(0.78, 0.18) }, '#13c2c2', '#b37feb')
  };
  
  const docDelivery = {
    trend: generateTrendData(0.92, 0.08),
    byDepartment: generateDepartmentData(0.92, 0.1),
    trendSeries: prepareDataByDepartment('doc', { byDepartment: generateDepartmentData(0.92, 0.1) }, '#722ed1', '#eb2f96')
  };
  
  const fileDelivery = {
    trend: generateTrendData(0.88, 0.11),
    byDepartment: generateDepartmentData(0.88, 0.13),
    trendSeries: prepareDataByDepartment('file', { byDepartment: generateDepartmentData(0.88, 0.13) }, '#fa8c16', '#fa541c')
  };
  
  // 生成数字化工具数据
  const toolsData = generateToolsData();
  const toolsDetailData = prepareToolsDetailData(toolsData);
  const digitalToolsByDepartment = prepareDigitalToolsByDepartment(toolsData);
  const toolsTrendData = prepareToolsUsageTrendData();
  
  // 准备趋势系列数据
  const trendSeries = departments.map((dept, index) => {
    return {
      name: dept,
      type: 'line',
      data: toolsTrendData[dept].map(item => item.value),
      smooth: true,
      symbol: 'emptyCircle',
      symbolSize: 8,
      lineStyle: {
        width: 3
      },
      emphasis: {
        focus: 'series',
        lineStyle: {
          width: 5
        }
      }
    };
  });
  
  const digitalTools = {
    toolsData,
    categories: toolsData.map(tool => tool.name),
    toolsDetailSeries: toolsDetailData.series,
    byDepartmentSeries: digitalToolsByDepartment.series,
    trendData: toolsTrendData,
    trendSeries
  };
  
  return {
    departments,
    months,
    componentStorage,
    circuitMaintenance,
    docDelivery,
    fileDelivery,
    digitalTools
  };
}